package cn.fastpay.management.service.impl;

import cn.fastpay.core.exception.BaseException;
import cn.fastpay.management.entity.PermissionAction;
import cn.fastpay.management.repository.PermissionActionRepository;
import cn.fastpay.management.service.PermissionActionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author freewolf
 */
@Service
public class PermissionActionServiceImpl implements PermissionActionService {

    @Autowired
    private PermissionActionRepository permissionActionRepository;

    @Override
    public Page<PermissionAction> getPage(int page, int pageSize) {
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = new PageRequest(page, pageSize, sort);
        return this.permissionActionRepository.findAll(pageable);
    }

    @Override
    public List<PermissionAction> getAll(){
        return this.permissionActionRepository.findAll();
    }

    @Override
    public void deleteById(Long id) {
        this.permissionActionRepository.delete(id);
    }

    @Override
    public void add(PermissionAction action) {
        if (action.getId() != null) {
            throw BaseException.DB_INSERT_INCLUDE_ID;
        } else {
            this.permissionActionRepository.save(action);
        }
    }

    @Override
    public void update(PermissionAction action) {
        if(action.getId() == null) {
            throw BaseException.DB_UPDATE_NOT_INCLUDE_ID;
        }
        permissionActionRepository.save(action);
    }

    @Override
    public PermissionAction getById(Long id) {
        return this.permissionActionRepository.findOne(id);
    }
}
